package com.test.mytest.swing;
/**
 * @author  <a href="mailto:foohsinglong@gmail.com">kevin.long</a>
 * @description Java获取系统软件安装列表,代码核心来自网上,主要通过Runtime实现,
 *  用JNI也行,解决乱码问题
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
 
public class SystemSoftware {  
    private JFrame f = new JFrame("本系统已经安装的软件列表");
    private JTextPane textPane = new JTextPane();
    private MyTable myTable=new MyTable();
    public static Charset charset = Charset.forName("GBK");
    public SystemSoftware() {
    	try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e2) {
			e2.printStackTrace();
		}
    	
        f.setLocation(300, 200);
        f.setSize(800,500);
        JScrollPane jScrollPane = new JScrollPane(myTable.getTable());
        f.getContentPane().add(jScrollPane);
        
        JPanel panel = new JPanel();
        f.getContentPane().add(panel, BorderLayout.NORTH);
        
        JButton button = new JButton("卸载");
        button.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e) {
        		int[] selectedColumns = myTable.jTable.getSelectedRows();
        		if (selectedColumns==null||selectedColumns.length<=0) {
					return;
				}
        		int i = selectedColumns[0];
        		System.out.println(i);
        		Object[] objects = myTable.data[i];
        		int showConfirmDialog = JOptionPane.showConfirmDialog(panel, objects[0]);
        		if (showConfirmDialog!=JOptionPane.OK_OPTION) {
					return;
				}
        		try {
					Runtime.getRuntime().exec(objects[3].toString());
				} catch (IOException e1) {
					e1.printStackTrace();
				}
        	}
        });
        panel.add(button);
        f.setVisible(true);
        f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);

        try {
            check();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    Map<String, String[]> mapMessage=new HashMap<>();
    private void check() throws Exception {
    	ExecutorService cachedThreadPool = Executors.newFixedThreadPool(20);
        textPane.setText("您已经安装的软件：");
        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        process = runtime
                .exec("cmd /c reg query HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\");
        BufferedReader in = new BufferedReader(new InputStreamReader(process
                .getInputStream(),"GBK"));
        String string = null;
        while ((string = in.readLine()) != null) {
        	String s=string;
            Runnable runnable = new Runnable() {
				public void run() {
					try {
						System.out.println(s);
						String[] message = queryValue(s);
						if (message != null) {
							message[4]=s.substring(s.lastIndexOf("\\")+1);
							System.out.println(s+"===="+message[0]);
							mapMessage.put(s, message);
							myTable.addRow(message);
						}
						f.repaint();
					} catch (IOException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
				}
			};
			cachedThreadPool.submit(runnable);
        }
        in.close();
        process.destroy();

    }

    //具体查询每一个软件的详细信息
    private String[] queryValue(String string) throws IOException {
        String nameString = "";
        String versionString = "";
        
        String publisherString="";
        String uninstallPathString = "";
        
        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        BufferedReader br = null;
        
        process = runtime.exec("cmd /c reg query " + string + " /v DisplayName");
        br = new BufferedReader(new InputStreamReader(process
                .getInputStream(),"GBK"));
        br.readLine();br.readLine();//去掉前两行无用信息
        if((nameString=br.readLine())!=null){
            nameString=nameString.replaceAll("DisplayName    REG_SZ    ", "");    //去掉无用信息
        }
        process.destroy();
        br.close();
        if (nameString==null) {
			return null;
		}

        process = runtime.exec("cmd /c reg query " + string + " /v DisplayVersion");
        br = new BufferedReader(new InputStreamReader(process
                .getInputStream(),"GBK"));
        br.readLine();br.readLine();//去掉前两行无用信息
        if((versionString=br.readLine())!=null){
            versionString=versionString.replaceAll("DisplayVersion    REG_SZ    ", "");    //去掉无用信息
        }
        process.destroy();
        br.close();
        process = runtime.exec("cmd /c reg query " + string + " /v Publisher");
        br = new BufferedReader(new InputStreamReader(process
                .getInputStream(),"GBK"));
        br.readLine();br.readLine();//去掉前两行无用信息
        if((publisherString=br.readLine())!=null){
            publisherString =publisherString.replaceAll("Publisher    REG_SZ    ", "");    //去掉无用信息
        }
        process.destroy();
        br.close();
        process = runtime.exec("cmd /c reg query " + string + " /v UninstallString");
        br = new BufferedReader(new InputStreamReader(process
                .getInputStream(),"GBK"));
        br.readLine();br.readLine();//去掉前两行无用信息
        if((uninstallPathString=br.readLine())!=null){
            uninstallPathString=uninstallPathString.replaceAll("UninstallString    REG_SZ    ", "");    //去掉无用信息
        }
        process.destroy();
        br.close();
        String[] resultString=new String[5];
        resultString[0]= nameString ;//== null ? null : new String(nameString.getBytes(),"GB-2312");
        resultString[1]= versionString ;//== null ? null : new String(versionString.getBytes(),"GB-2312");
        resultString[2]= publisherString ;//== null ? null : new String(publisherString.getBytes(),"GB-2312");
        resultString[3]= uninstallPathString ;//== null ? null : new String(uninstallPathString.getBytes(),"GB-2312");
        return resultString;
    }
    
    //列表
    private class MyTable{
        private JTable jTable;
        private Object[][] data=new Object[1000][5];
        private Object[] colNames= { "软件名称","版本号","出版商","卸载路径","标识"};
        private int p=-1;
        
        public MyTable(){
            
        }
        
        public void addRow(Object[] data){
            p++;
            this.data[p]=data;
        }
        
        
        public JTable getTable(){
            jTable=new JTable(data,colNames);
            return jTable;
        }
        
    }
    
    public static void main(String[] args) {
        new SystemSoftware();
    }
}